package xin.cymall.controller;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import xin.cymall.annotation.SysLog;
import xin.cymall.entity.File;
import xin.cymall.enumresource.StateEnum;
import xin.cymall.service.FileService;
import xin.cymall.utils.PageUtils;
import xin.cymall.utils.Query;
import xin.cymall.utils.R;
import xin.cymall.utils.UUID;


/**
 * 地产附件表
 * 
 * @author mhj
 * @email qq254784163@qq.com
 * @date 2017-11-17 11:52:01
 */
@Controller
@RequestMapping("file")
public class FileController {
	@Autowired
	private FileService fileService;
	@RequestMapping("/list")
    public String list() {
        return "file/list";
    }
	/**
	 * 列表
	 */
    @ResponseBody
	@RequestMapping("/listData")
	@RequiresPermissions("file:list")
	public R list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);

		List<File> fileList = fileService.getList(query);
		int total = fileService.getCount(query);
		
		PageUtils pageUtil = new PageUtils(fileList, total, query.getLimit(), query.getPage());
		
		return R.ok().put("page", pageUtil);
	}

    /**
     * 跳转到新增页面
     **/
    @RequestMapping("/add")
    @RequiresPermissions("file:save")
    public String add(){
        return "file/add";
    }

    /**
     *   跳转到修改页面
     **/
    @RequestMapping("/edit/{id}")
    @RequiresPermissions("file:update")
    public String edit(Model model, @PathVariable("id") String id){
		File file = fileService.get(id);
        model.addAttribute("model",file);
        return "file/edit";
    }

	/**
	 * 信息
	 */
    @ResponseBody
    @RequestMapping("/info/{id}")
    @RequiresPermissions("file:info")
    public R info(@PathVariable("id") String id){
        File file = fileService.get(id);
        return R.ok().put("file", file);
    }

    /**
	 * 保存
	 */
    @ResponseBody
    @SysLog("保存地产附件表")
	@RequestMapping("/save")
	@RequiresPermissions("file:save")
	public R save(@RequestBody File file){
		fileService.save(file);
		
		return R.ok();
	}
	
	/**
	 * 修改
	 */
    @ResponseBody
    @SysLog("修改地产附件表")
	@RequestMapping("/update")
	@RequiresPermissions("file:update")
	public R update(@RequestBody File file){
		fileService.update(file);
		
		return R.ok();
	}

    /**
     * 启用
     */
    @ResponseBody
    @SysLog("启用地产附件表")
    @RequestMapping("/enable")
    @RequiresPermissions("file:update")
    public R enable(@RequestBody String[] ids){
        String stateValue= StateEnum.ENABLE.getCode();
		fileService.updateState(ids,stateValue);
        return R.ok();
    }
    /**
     * 禁用
     */
    @ResponseBody
    @SysLog("禁用地产附件表")
    @RequestMapping("/limit")
    @RequiresPermissions("file:update")
    public R limit(@RequestBody String[] ids){
        String stateValue=StateEnum.LIMIT.getCode();
		fileService.updateState(ids,stateValue);
        return R.ok();
    }
	
	/**
	 * 删除
	 */
    @ResponseBody
    @SysLog("删除地产附件表")
	@RequestMapping("/delete")
	@RequiresPermissions("file:delete")
	public R delete(@RequestBody String[] ids){
		fileService.deleteBatch(ids);
		
		return R.ok();
	}
    /**
     * `images` mediumblob COMMENT '图片流',  数据库
     *  images  byte[] java
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/upload")
    @ResponseBody
    public R upload(@RequestParam(value = "file") MultipartFile multipartFile,
                       HttpServletRequest request) throws Exception {
        try {
        	 File file = new File();
        	 file.setUploadId(UUID.getCode(9));
             String fileName = multipartFile.getOriginalFilename();
             file.setFileName(fileName);
             byte[] images = multipartFile.getBytes();
             file.setImages(images);
             file.setCreateTime(new Date());
             fileService.save(file);
             return R.ok().put("uuid", file.getUploadId());
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
     }
	@RequestMapping("showImage/{uuid}")
    @ResponseBody
    public byte[] showImage(@PathVariable("uuid") String uuid, HttpServletResponse response) throws Exception {
		File file = fileService.get(uuid);
        if(file==null){
               throw new IllegalAccessException();
        }
        byte[] images = file.getImages();
        String fileName =file.getFileName().toLowerCase();
        if (fileName.lastIndexOf(".jpg") == -1 && fileName.lastIndexOf(".png") == -1
                   && fileName.lastIndexOf(".jpeg") == -1 && fileName.lastIndexOf(".gif") == -1
                   && fileName.lastIndexOf(".bmp") == -1) {
               BufferedInputStream bis = null;
               ServletOutputStream fos = null;
               byte[] buf = new byte[1024];
               int size = 0;
               bis = new BufferedInputStream(new ByteArrayInputStream(images));
               response.setContentType("multipart/form-data");
               String realfilename = "";
               try {
                   //防止乱码
                   realfilename = new String(file.getFileName().getBytes("UTF-8"), "ISO8859-1");
               } catch (UnsupportedEncodingException e) {
                   e.printStackTrace();
               }
               //设置文件名
               response.setHeader("Content-Disposition", "attachment;fileName=" + realfilename);
               fos = response.getOutputStream();
               while ((size = bis.read(buf)) != -1)
                   fos.write(buf, 0, size);
               fos.close();
               bis.close();
               return null;
        }
        return images;
    }  
}
